# -*- coding: utf-8 -*-
import KBEngine
from KBEDebug import *
from ComFun import *
import time
import random
import d_items
import d_server
import d_task
import d_weather

class Field:
    def __init__(self):
        if self.fieldNum <= 0:
            self.fieldNum = d_server.InitFieldNum

    def getFieldData(self, index):
        for i,fieldData in enumerate(self.fieldList):
            if index == fieldData["index"]:
                return i
        return None

    def getStage(self, index):
        i = self.getFieldData(index)
        fieldData = self.fieldList[i]
        cropId = fieldData["cropId"]
        stageTime = d_items.items[cropId]["time"] // d_items.items[cropId]["stage"]
        curStage = (int(time.time()) - fieldData["plantTime"]) // stageTime + 1
        return curStage

    def isRipe(self, index, paramTime=0):
        #指定地块的农作物是否成熟
        if paramTime <= 0:
            paramTime = int(time.time())
        i = self.getFieldData(index)
        fieldData = self.fieldList[i]
        cropId = fieldData["cropId"]
        effectTime = 0  #道具施加在作物上影响的时间
        for prop in fieldData["propList"]:
            print("isRipe ==>> prop : ",prop)
            if d_items.items["prop_effect_time"]["value"] == d_items.items[prop["itemId"]]["effect_type"]:
                effectTime = effectTime + self.prop_effect_time(prop["itemId"]) * prop["number"]
        stageTime = d_items.items[cropId]["time"] // d_items.items[cropId]["stage"]
        curStage = (paramTime - fieldData["plantTime"] + effectTime) // stageTime + 1
        finalStage = d_items.items[cropId]["stage"] + 1
        if curStage >= finalStage:
            return True
        return False

    def calcScore(self, fieldData):
        #计算指定地块农作物的产量
        if not fieldData:
            return 2
        #灾害生效
        effectRatio = 0.0
        for disasterId in fieldData["disasterList"]:
            effectRatio += d_weather.disaster[disasterId]["effect"]
        if fieldData["disasterId"] > 0:
            effectRatio += d_weather.disaster[fieldData["disasterId"]]["effect"]
        #化肥生效
        for prop in fieldData["propList"]:
            if d_items.items["prop_effect_yield"]["value"] == d_items.items[prop["itemId"]]["effect_type"]:
                effectRatio += self.prop_effect_yield(prop["itemId"]) * prop["number"]
        effectRatio /= d_server.RandomBase
        cropId = fieldData["cropId"]
        finalScore = int(d_items.items[cropId]["score"] * (1.0 + effectRatio))
        #被偷生效
        finalScore -= fieldData["stealScore"]
        if finalScore < d_items.items[cropId]["mreward"]:
            finalScore = d_items.items[cropId]["mreward"]
        return int(finalScore)

    def plant(self, index, cropId):
        #客户端请求种植
        if index <= 0 or index > self.fieldNum:
            # self.promptClient("FieldIndex")
            return 2
        if None != self.getFieldData(index):
            self.promptClient("HadPlant")
            return 1
        if cropId not in d_items.items:
            self.promptClient("SeedNotExist")
            return 1
        if d_items.items[cropId]["rate"] <= 0:
            return 2
        if self.getItemNum(cropId) <= 0:
            self.promptClient("ItemLess")
            return 1
        newFieldData = {
            "index": index,
            "cropId": cropId,
            "plantTime": int(time.time()),
            "disasterId": 0,
            "disasterList": [],
            "stealScore": 0,
            "stealList": [],
            "propList": []
        }
        self.fieldList.append(newFieldData)
        self.fieldList = self.fieldList
        #消耗种子、发送数据到任务模块、通知客户端
        self.addItem(cropId, -1)
        self.task_daily_update(d_task.task["mode_plant"]["value"], 1, cropId)
        self.client.onPlant(index, cropId)
        self.updateToWatcher(d_server.UpdateType.FieldList, {})
        self.updateToWatcher(d_server.UpdateType.Plant, {"index":index,"cropId":cropId})

    def harvest(self, index):
        #客户端请求收获
        if index <= 0 or index > self.fieldNum:
            # self.promptClient("FieldIndex")
            return 2
        i = self.getFieldData(index)
        if i is None:
            # self.promptClient("CropNotExist")
            return 2
        #检测农作物阶段
        if not self.isRipe(index):
            self.promptClient("CropNoRipe")
            return 1
        #计算本次收获的积分
        fieldData = self.fieldList[i]
        cropId = fieldData["cropId"]
        finalScore = self.calcScore(fieldData)
        self.addScore(finalScore, d_server.ScoreType.Harvest)
        # 删除农作物
        del self.fieldList[i]
        self.fieldList = self.fieldList
        # 通知客户端
        self.client.onHarvest(index, finalScore)
        #发送数据到任务模块
        self.task_daily_update(d_task.task["mode_harvest"]["value"], 1, cropId)
        self.updateToWatcher(d_server.UpdateType.FieldList, {})
        self.updateToWatcher(d_server.UpdateType.Harvest, {"index":index})

    def expand(self):
        #客户端请求扩建地块
        if self.fieldNum >= d_server.TotalField:
            self.promptClient("AllHadExpand")
            return 1
        self.fieldNum += 1
        self.client.onExpand(self.fieldNum)
        self.updateToWatcher(d_server.UpdateType.FieldNum, {})

    def checkDisaster(self, paramTime=0):
        #检测灾害触发
        addDisasterList = []
        for fieldData in self.fieldList:
            if fieldData["disasterId"] <= 0:
                if not self.isRipe(fieldData["index"], paramTime):
                    #检测是否只剩下保底收入
                    curScore = self.calcScore(fieldData)
                    cropId = fieldData["cropId"]
                    if curScore <= d_items.items[cropId]["mreward"]:
                        continue
                    #按照概率触发
                    randRes = random.randint(1, d_server.RandomBase)
                    if randRes <= d_weather.weather[self.weatherId]["triggerratio"]:
                        fieldData["disasterId"] = d_weather.weather[self.weatherId]["disaster"]
                        addDisasterList.append(fieldData["index"])
        if len(addDisasterList) > 0:
            if self.client:
                self.client.addDisaster(self.weatherId, addDisasterList)
            params = {"weatherId":self.weatherId,"fieldIndexArray":addDisasterList}
            self.updateToWatcher(d_server.UpdateType.AddDisaster, params)
            return True
        return False

    def effectDisaster(self):
        #农作物当前灾害生效
        isEffect = False
        for fieldData in self.fieldList:
            if fieldData["disasterId"] > 0:
                fieldData["disasterList"].append(fieldData["disasterId"])
                fieldData["disasterId"] = 0
                isEffect = True
        return isEffect

    def clearDisaster(self, index):
        #客户端请求清除灾害
        if index <= 0 or index > self.fieldNum:
            # self.promptClient("FieldIndex")
            return 2
        i = self.getFieldData(index)
        if i is None:
            # self.promptClient("CropNotExist")
            return 2
        #检测农作物阶段
        if self.isRipe(index):
            self.promptClient("CropHadRipe")
            return 1
        fieldData = self.fieldList[i]
        if fieldData["disasterId"] > 1:
            taskMode = 0
            if fieldData["disasterId"] == 2:
                taskMode = d_task.task["mode_water"]["value"]
            elif fieldData["disasterId"] == 3:
                taskMode = d_task.task["mode_weed"]["value"]
            elif fieldData["disasterId"] == 4:
                taskMode = d_task.task["mode_worm"]["value"]
            fieldData["disasterId"] = 0
            self.fieldList = self.fieldList
            self.addScore(d_server.ClearDisasterScore, d_server.ScoreType.Disaster)
            self.client.onClearDisaster(index)
            # 发送数据到任务模块
            self.task_daily_update(taskMode, 1)
            self.updateToWatcher(d_server.UpdateType.FieldList, {})
            self.updateToWatcher(d_server.UpdateType.ClearDisaster, {"index":index})

    def friendSteal(self, accountRef, dbid, index, nickName):
        #好友偷本人的菜
        if not self.isFriend(dbid):
            accountRef.promptClient("NotFriend")
            return 1
        i = self.getFieldData(index)
        if i is None:
            # accountRef.promptClient("CropNotExist")
            return 2
        #检测农作物是否成熟
        if not self.isRipe(index):
            accountRef.promptClient("CropNoRipe")
            return 1
        #检测是否已经偷过
        fieldData = self.fieldList[i]
        if dbid in fieldData["stealList"]:
            accountRef.promptClient("HadSteal")
            return 1
        #检测当前积分
        cropId = fieldData["cropId"]
        curScore = self.calcScore(fieldData)
        if curScore <= d_items.items[cropId]["mreward"]:
            accountRef.promptClient("MinScore")
            return 1
        #检测护盾
        if self.isShielding():
            accountRef.promptClient("IsShielding")
            return 1
        #添加到已偷取列表
        fieldData["stealList"].append(dbid)
        #随机偷取积分
        randRes = random.randint(d_server.StealMinRatio, d_server.StealMaxRatio)
        randRes /= d_server.RandomBase
        stealScore = int(randRes * d_items.items[cropId]["score"])
        if stealScore < d_server.StealMinScore:
            stealScore = d_server.StealMinScore
        if curScore - stealScore < d_items.items[cropId]["mreward"]:
            stealScore = curScore - d_items.items[cropId]["mreward"]
        #本人扣除积分
        fieldData["stealScore"] += stealScore
        # 添加被好友偷取的动态
        self.mailOptOTM(1, nickName, fieldData["cropId"], stealScore, int(time.time()))
        self.fieldList = self.fieldList
        #好友增加积分
        accountRef.task_daily_update(d_task.task["mode_steal"]["value"], 1, fieldData["cropId"])
        accountRef.addScore(stealScore, d_server.ScoreType.Steal)
        accountRef.stealSuccess(index, stealScore)
        self.updateToWatcher(d_server.UpdateType.FieldList, {})

    def friendHelp(self, accountRef, dbid, index, nickName):
        #好友帮忙清除灾害
        if not self.isFriend(dbid):
            accountRef.promptClient("NotFriend")
            return 1
        i = self.getFieldData(index)
        if i is None:
            # accountRef.promptClient("CropNotExist")
            return 2
        #检测农作物阶段
        if self.isRipe(index):
            accountRef.promptClient("CropHadRipe")
            return 1
        fieldData = self.fieldList[i]
        if fieldData["disasterId"] > 1:
            # 添加被好友清除灾害的动态
            self.mailOptOTM(fieldData["disasterId"], nickName,
                            fieldData["cropId"], d_server.ClearDisasterScore, int(time.time()))
            fieldData["disasterId"] = 0
            self.fieldList = self.fieldList
            if self.client:
                self.client.onClearDisaster(index)
            taskMode = 0
            if fieldData["disasterId"] == 2:
                taskMode = d_task.task["mode_water"]["value"]
            elif fieldData["disasterId"] == 3:
                taskMode = d_task.task["mode_weed"]["value"]
            elif fieldData["disasterId"] == 4:
                taskMode = d_task.task["mode_worm"]["value"]
            accountRef.task_daily_update(taskMode, 1, fieldData["cropId"])
            # 好友增加积分
            accountRef.addScore(d_server.ClearDisasterScore, d_server.ScoreType.Help)
            self.updateToWatcher(d_server.UpdateType.FieldList, {})
            self.updateToWatcher(d_server.UpdateType.ClearDisaster, {"index": index})

